#include <webx/route.h>
#include <dbentity/T_XG_FILE.h>
#include <dbentity/T_XG_NOTE.h>

class EditNote : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(EditNote)

int EditNote::process()
{
	param_string(id);
	param_string(flag);
	param_string(icon);
	param_string(level);
	param_string(title);
	param_string(folder);
	param_string(remark);
	param_string(content);
	param_string(deficon);
	
	if (deficon.empty()) deficon = "/res/img/note/note.png";

	checkLogin();

	int res = 0;
	string sqlcmd;
	CT_XG_NOTE tab;
	sp<DBConnect> dbconn = webx::GetDBConnect(token->getDataId());
	string user = folder == "WEBPAGE" ? "system" : token->getUser();

	auto removeNote = [](sp<DBConnect> dbconn, const string& id){
		string sqlcmd = "DELETE FROM T_XG_FILE WHERE TYPE='NOTE' AND RID=?";

		if (dbconn->execute(sqlcmd, id) < 0) return XG_SYSERR;

		sqlcmd = "DELETE FROM T_XG_NOTE WHERE ID=?";

		return dbconn->execute(sqlcmd, id);
	};

	tab.init(dbconn);
	tab.id = id;

	if (flag == "A" || flag == "C" || flag == "R")
	{
		webx::CheckFileName(title, 0);
		webx::CheckFileName(folder, 0);

		if ((flag == "A" && title.empty()) || (flag == "C" && folder == "WEBPAGE")) return simpleResponse(XG_PARAMERR);

		if (icon.empty())
		{
			if (flag == "C")
			{
				icon = "/res/img/menu/folder.png";
			}
			else
			{
				icon = deficon;
			}
		}

		if (flag == "R")
		{
			vector<string> vec;

			sqlcmd = "USER=? AND FOLDER=? ORDER BY ID DESC";

			if (!tab.findWhere(sqlcmd, user, folder)) return simpleResponse(XG_SYSERR);

			while (tab.next()) vec.push_back(tab.id.val());

			dbconn->begin();

			for (const string& id : vec)
			{
				if (removeNote(dbconn, id) < 0)
				{
					dbconn->rollback();

					return simpleResponse(XG_SYSERR);
				}
			}

			dbconn->commit();

			res = vec.size();
		}
		else
		{
			sp<RowData> row;
			sp<QueryResult> rs;

			sqlcmd = "SELECT COUNT(*) FROM T_XG_NOTE WHERE USER=?";

			if (!(rs = dbconn->query(sqlcmd, user))) return simpleResponse(XG_SYSERR);

			if ((row = rs->next()) && row->getInt(0) > 1000) return simpleResponse(XG_AUTHFAIL);

			param_int(type);

			if (level.empty()) level = "1";

			if (type < 0 || type > 1) type = 0;

			if (type == 1 && flag == "A" && content.empty()) content = "## Markdwon Editor";

			tab.type = type;
			tab.user = user;
			tab.icon = icon;
			tab.level = level;
			tab.title = title;
			tab.folder = folder;
			tab.remark = remark;
			tab.content = content;
			tab.statetime.update();

			for (int i = 0; i < 5; i++)
			{
				tab.id = DateTime::GetBizId();
				tab.position = (int)(time(NULL));

				if ((res = tab.insert()) >= 0) break;
			}

			if (res > 0)
			{
				json["statetime"] = tab.statetime.toString();
				json["icon"] = tab.icon.toString();
				json["id"] = tab.id.val();
			}
		}
	}
	else if (flag == "D")
	{
		res = XG_NOTFOUND;

		if (tab.find() && tab.next() && user == tab.user.val() && folder == tab.folder.val())
		{
			res = removeNote(dbconn, id);
		}
	}
	else if (flag == "U")
	{
		res = XG_NOTFOUND;

		if (tab.find() && tab.next() && user == tab.user.val() && folder == tab.folder.val())
		{
			if (icon.length() > 0) tab.icon = icon;
			if (level.length() > 0) tab.level = level;
			if (title.length() > 0) tab.title = title;
			if (remark.length() > 0) tab.remark = remark;

			if (tab.position.val() == 0) tab.position = (int)(time(NULL));

			if (content.empty() > 0)
			{
				content = tab.content.toString();
			}
			else
			{
				tab.content = content;
			}
			
			tab.statetime.update();

			if ((res = tab.update()) < 0) return simpleResponse(res);

			string tmp = tab.icon.toString();
			
			if (tmp.length() < 128) json["icon"] = tmp;

			if (content.length() > 0)
			{
				string ids;
				size_t pos = 0;
				string tag = "/notefile?id=";

				while ((pos = content.find(tag, pos)) != string::npos)
				{
					pos += tag.length();
					ids += "'" + stdx::str(stdx::atol(content.c_str() + pos)) + "',";
				}

				if (ids.length() > 0)
				{
					ids.pop_back();

					stdx::format(sqlcmd, "DELETE FROM T_XG_FILE WHERE TYPE='NOTE' AND RID=? AND ID NOT IN (%s)", ids.c_str());
				}
				else
				{
					sqlcmd = "DELETE FROM T_XG_FILE WHERE TYPE='NOTE' AND RID=?";
				}
				
				dbconn->execute(sqlcmd, id);
			}
		}
	}
	else if (flag == "M")
	{
		int position = 0;
		vector<string> vec = stdx::split(folder, ",");

		if (vec.empty()) return simpleResponse(XG_PARAMERR);

		dbconn->begin();

		if (vec.size() > 1)
		{
			const char* sql = "UPDATE T_XG_NOTE SET POSITION=? WHERE FOLDER=? AND (TITLE IS NULL OR TITLE='')";

			for (string& folder : vec)
			{
				dbconn->execute(sql, ++position, folder);
			}
		}
		else
		{
			vec = stdx::split(title, ",");

			const char* sql = "UPDATE T_XG_NOTE SET POSITION=? WHERE FOLDER=? AND TITLE=?";

			for (string& title : vec)
			{
				dbconn->execute(sql, ++position, folder, title);
			}
		}

		dbconn->commit();

		res = vec.size();
	}
	else
	{
		res = XG_PARAMERR;
	}

	json["code"] = res;
	out << json;
	
	return XG_OK;
}